package memory;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class ThreadInformation {
	private ThreadMXBean tmxbean;
	private boolean isCPU;
	private long allThreadsId[];
	private int nbThreads;
	private long totalThread;
	private static final int MAX_STACK_TRACE_ELT=10;
	private int peakThreadCount;
	
	public ThreadInformation(){
		tmxbean=ManagementFactory.getThreadMXBean();
		/*
		 * know that a Java virtual machine supports measuring 
		 of the CPU time for any thread
		 */
		isCPU=tmxbean.isThreadCpuTimeSupported();
		nbThreads=tmxbean.getThreadCount();
		allThreadsId=new long[nbThreads];
		allThreadsId=tmxbean.getAllThreadIds();
		totalThread=tmxbean.getTotalStartedThreadCount();
		peakThreadCount=tmxbean.getPeakThreadCount();
		//isCPU=tmxbean.isCurrentThreadCpuTimeSupported();
		//isCPU=ManagementFactory.
	}
	
	public int getMAX_STACK_TRACE_ELT(){
		return MAX_STACK_TRACE_ELT;
	}
	
	public ThreadMXBean getTmxbean(){
		return tmxbean;
	}
	
	public boolean getIsCPU(){
		return isCPU;
	}
	
	public long getTotalThread(){
		return totalThread;
	}
	
	public int getNbThreads(){
		return nbThreads;
	}
	
	public long[] getAllThreadsId(){
		return allThreadsId;
	}
	
	public ThreadInfo getThreadInfo(long id){
		return tmxbean.getThreadInfo(id,MAX_STACK_TRACE_ELT);
	}
	
	public int getPeakThreadCount(){
		return this.peakThreadCount;
	}
	
	public String affichageInfoThread(long id){
		String retour=null;
		ThreadInfo tinf=tmxbean.getThreadInfo(id);
		String tName=tinf.getThreadName();
		long tId=tinf.getThreadId();
		String  tState=tinf.getThreadState().name();
		retour="<b>Thread's name:</b>" + tName + "<b>State: </b>" + tState;
		return retour;
		//tState.name();
	}
	
	public StackTraceElement[] getStackTrace(long id){
		StackTraceElement[] tabs=new StackTraceElement[this.MAX_STACK_TRACE_ELT];
		ThreadInfo tti=this.getThreadInfo(id);
		tabs=tti.getStackTrace();
		return tabs;
	}
	
	/*public static void main (String[] args){
		ThreadInformation tinf=new ThreadInformation();
		for (int i=0; i<tinf.getNbThreads();i++){
			System.out.println("Thread "+ i + " --> "+ tinf.affichageInfoThread(tinf.allThreadsId[i]));
		}
	}*/
	
}
